package org.shop.controller.manager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.ShufflingInstall;
import org.shop.service.ShufflingInstallService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class ManagerShufflingController {

	private static Logger logger = LogManager.getLogger(ManagerShufflingController.class);
	
	@Autowired
    private ShufflingInstallService shufflingInstallService;
	
	
	/**
	 * 添加轮播图设置
	 * @param req
	 * @return
	 */
	@RequestMapping("manager/addShufflingInstall")
	@ResponseBody
	public Map<String,Object> addShufflingInstall(HttpServletRequest req) {
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		//转换成多部分request  
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
		//获取的值
		int time = Integer.parseInt(multiRequest.getParameter("time"));
		String shufflingDescribe = multiRequest.getParameter("shufflingDescribe");
		//解析前台传来的数组（照片路径）
		String[] photoUrlArray = multiRequest.getParameterValues("photoUrl");
		String photoUrlArrayValue = "";
		for (String photoUrlArrayString : photoUrlArray) {
			if(photoUrlArrayString.trim() !=""){
				if("".equals(photoUrlArrayValue)){
					photoUrlArrayValue+=photoUrlArrayString;
				}else{
					photoUrlArrayValue+=","+photoUrlArrayString;;
				}
			}
		}
		//解析前台传来的数组（照片描述）
		String[] photoDescribeArray = multiRequest.getParameterValues("photoDescribe");
		String photoDescribeArrayValue = "";
		for (String photoDescribeArrayString : photoDescribeArray) {
			if(photoDescribeArrayString.trim() !=""){
				if("".equals(photoDescribeArrayValue)){
					photoDescribeArrayValue+=photoDescribeArrayString;
				}else{
					photoDescribeArrayValue+=","+photoDescribeArrayString;;
				}
			}
		}
		Map<String, Object> map=new HashMap<String, Object>();
    	String photoStr="";
		FTPClient ftpClient =null;
		InputStream is = null;
		try{
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
					//取得上传文件
    				List<MultipartFile> fileList = multiRequest.getFiles(name);
    				if(fileList!=null){
    					for(MultipartFile file:fileList){
    						if(file != null){
    							//取得当前上传文件的文件名称
    	    					String myFileName = file.getOriginalFilename();
    	    					myFileName=FtpUtil2.generateFileName(myFileName);
    	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
    	    					if(myFileName.trim() !=""){
    	    						myFileName=FtpUtil2.generateFileName(myFileName);
    	    						 //按照比例进行缩小和放大
                                    is=file.getInputStream();
                                    int len=is.available();
                                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                    if(len/1024>700) {//kb
                                    	//按照比例进行缩小和放大
                                        Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                    }
    	    						FtpUtil2.upload(myFileName, is, ftpClient);
    	    						if("".equals(photoStr)){
    	    							photoStr+=ftp_photoDirectory+"/"+myFileName;
    	    						}else{
    	    							photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
    	    						}
    	    					}
    						}
    					}
    				}
				}
    			ShufflingInstall shufflingInstall = new ShufflingInstall();
    			shufflingInstall.setTime(time);
    			shufflingInstall.setPhotoDescribe(photoDescribeArrayValue);
    			shufflingInstall.setPhotoUrl(photoUrlArrayValue);
    			shufflingInstall.setShufflingDescribe(shufflingDescribe);
    			shufflingInstall.setSchedulePhoto(photoStr);
    			int num = shufflingInstallService.insertSelective(shufflingInstall);
    			map.put("state", num);
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    	}finally {
    		try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
		}
		return map;
	}
	
	
	/**
	 * 获取所有得轮播图
	 * @param req
	 * @return
	 */
	@RequestMapping("manager/getShufflingInfoList")
	@ResponseBody
	public Map<String,Object> getShufflingInfoList(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> pramMap = new HashMap<String,Object>();
		String shufflingDescribe = req.getParameter("shufflingDescribe");
	 	String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
		try {
			pramMap.put("startPage", Integer.parseInt(currentPage));
			pramMap.put("pageSize", Integer.parseInt(pageSize));
			pramMap.put("shufflingDescribe", shufflingDescribe);
			map = shufflingInstallService.getAllShufflingInfo(pramMap);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
	/**
	 * 启用轮播
	 * @param req
	 * @return
	 */
	@RequestMapping("manager/enabledShuffling")
	@ResponseBody
	public int enabledShuffling(HttpServletRequest req) {
		int num = 0;
		Long shufflingId = Long.parseLong(req.getParameter("shufflingId"));
		try {
			ShufflingInstall shufflingInstall = new ShufflingInstall();
			shufflingInstall.setShufflingId(shufflingId);
			shufflingInstall.setDefaultState((byte) 1);
			shufflingInstallService.updateByPrimaryKeySelective(shufflingInstall);
			shufflingInstallService.updateAllShufflingOfDefaultState(shufflingId);
			num = 1;
		}catch(Exception e) {
			num = 0;
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	
	/**
	 * 删除轮播图
	 * @param req
	 * @return
	 */
	@RequestMapping("manager/delShuffling")
	@ResponseBody
	public int delShuffling(HttpServletRequest req) {
		Long shufflingId = Long.parseLong(req.getParameter("shufflingId"));
		int num = 0;
		try {
			num = shufflingInstallService.deleteByPrimaryKey(shufflingId);
		}catch(Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return num;
	}
	
	
	
}
